package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.Utils.PageUtil;
import com.example.haoqisystem.entity.RegistrationForm;
import com.example.haoqisystem.request.CreateAndUpdateRegistrationFormRequest;
import com.example.haoqisystem.request.QueryRegistrationFormListRequest;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.response.PageResult;
import com.example.haoqisystem.respository.RegistrationFormRepository;
import com.example.haoqisystem.respository.StudentRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor_ ={@Autowired} )
public class RegistrationFormService {
    
    private final RegistrationFormRepository registrationFormRepository;

    
    //提交报名表
    public BaseResponse<RegistrationForm> add(CreateAndUpdateRegistrationFormRequest request) {
        try {
            RegistrationForm form = new RegistrationForm();
            BeanUtil.copyProperties(request, form, CopyOptions.create().setIgnoreNullValue(true));
            form.setIsPay(false);
            form.setIsObtainedMaterial(false);
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS, true, registrationFormRepository.save(form));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //更新报名表
    public BaseResponse<RegistrationForm> update(CreateAndUpdateRegistrationFormRequest request) {
        if(request.getId()==null){
            return new BaseResponse<>("报名表id不存在！",false,null);
        }
        try{
            Optional<RegistrationForm> form=registrationFormRepository.findByIdAndDeletedFalse(request.getId());
            if(!form.isPresent()){
                return new BaseResponse<>("该报名表不存在！",false,null);
            }
            RegistrationForm form1=form.get();
            BeanUtil.copyProperties(request,form1,CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,registrationFormRepository.save(form1));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //删除报名表
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<String> delete(Long id) {
        try{
           Optional<RegistrationForm> formOptional=registrationFormRepository.findByIdAndDeletedFalse(id);
            if(!formOptional.isPresent()){
                return new BaseResponse<>("该报名表不存在！",false,null);
            }
            RegistrationForm form=formOptional.get();
            form.setDeleted(true);
            registrationFormRepository.save(form);
            return new BaseResponse<>(ConstUtil.DELETED_SUCCESS,true,null);
        }catch (Exception e){
            return new BaseResponse<>(ConstUtil.DELETED_FALSE,false,e.toString());
        }
    }

    //分页查询报名表
    public BaseResponse<PageResult<RegistrationForm>> queryList(QueryRegistrationFormListRequest request) {
        try{
            List<RegistrationForm> forms= registrationFormRepository.findAll();
            PageResult<RegistrationForm> page= PageUtil.getPage(forms,request.getPageNum(),request.getPageSize());
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,page);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //跟据id查询报名表详情
    public BaseResponse<RegistrationForm> detail(Long id, boolean deleted) {
        try{
            Optional<RegistrationForm> form=registrationFormRepository.findByIdAndDeleted(id,deleted);
            if (!form.isPresent()){
                return new BaseResponse<>("不存在该报名表！",false,null);
            };
            RegistrationForm form1=form.get();
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,form1);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //查询报名表名单列表
    public List<RegistrationForm> getList() {
        try{
            List<RegistrationForm> list=registrationFormRepository.findAll();
            for(RegistrationForm form:list){
                if(form.getDeleted()){
                    list.remove(form);
                }
            }
            return list;
        }catch (Exception e){
            return null;
        }
    }

    //查询报名表名单，不分页
    public BaseResponse<List<RegistrationForm>> queryList1(String name,String companyName,
                                                           String lectureName,Long lectureId,Long id) {
        try{
            Specification<RegistrationForm> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                if(name!=null&&!name.equals("")){
                    String nameLike="%"+name+"%";
                    predicates.add(builder.like(root.get("name"),nameLike));
                }
                if(lectureName!=null&&!lectureName.equals("")){
                    String nameLike="%"+lectureName+"%";
                    predicates.add(builder.like(root.get("lectureName"),nameLike));
                }
                if(companyName!=null&&!companyName.equals("")){
                    String nameLike="%"+companyName+"%";
                    predicates.add(builder.like(root.get("companyName"),nameLike));
                }
                if(lectureId!=null){
                    predicates.add(builder.equal(root.get("lectureId"),lectureId));
                }
                if(id!=null&&!id.equals("")){
                    predicates.add(builder.equal(root.get("id"),id));
                }
                predicates.add(builder.equal(root.get("deleted"),false));
                return  builder.and(predicates.toArray(new Predicate[0]));
            };
            List<RegistrationForm> list=registrationFormRepository.findAll(specification);
            Collections.reverse(list);
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,list);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }
}
